package com.lagou.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 判断是否登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession();
        boolean flag = false;

        // 获取cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();

            // 判断cookie中的值与session中的值是否相同
            if (name.equals("USER")) {
                String value = (String) session.getAttribute(name);
                if (cookie.getValue().equals(value)) {
                    flag = true;
                }
            }
        }

        if (flag) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 如果不存在session 重定向到登录页面
            resp.sendRedirect("login/index.html");
        }
    }

    @Override
    public void destroy() {

    }
}
